package com.djhu.reactor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by zw on 2018/3/23.
 */
public class Dispatcher {
    private Map<EventType,List<EventHandler>> eventHandlerMap = new ConcurrentHashMap<>();


    private Selector selector;

    public void register(EventType eventType,EventHandler eventHandler){
        if (!eventHandlerMap.containsKey(eventType)){
            eventHandlerMap.put(eventType,new ArrayList<EventHandler>());
        }
        eventHandlerMap.get(eventType).add(eventHandler);
    }

    public void remove(EventType eventType,EventHandler eventHandler){
        if (!eventHandlerMap.containsKey(eventType)){
            return;
        }
        eventHandlerMap.get(eventType).remove(eventHandler);
    }

    public void dispatch(){
        List<Event> eventList = selector.select();
        for (Event event:eventList){
            EventType eventType = event.getEventType();
            List<EventHandler> eventHandlers = eventHandlerMap.get(eventType);
            for (EventHandler eventHandler:eventHandlers){
                eventHandler.handle(event);
            }
        }
    }

    public Selector getSelector() {
        return selector;
    }

    public void setSelector(Selector selector) {
        this.selector = selector;
    }
}